package com.youlai.netty.service.tcp.client;

import com.youlai.netty.service.tcp.BootNettyChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author zc
 * @date 2023-02-04 19:46
 */
@Slf4j
public class UDPClient {

    private Channel channel;

    public void connect(String host,int port){

            Bootstrap bootstrap = new Bootstrap();
            EventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new BootNettyChannelInitializer<>());
             channel = bootstrap.bind(8089).sync().channel();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public void send(String msg){
        InetSocketAddress address = new InetSocketAddress("localhost", 8088);
        ByteBuf byteBuf = Unpooled.copiedBuffer("你好服务器".getBytes(StandardCharsets.UTF_8));
        try {
            ChannelFuture sync = channel.writeAndFlush(new DatagramPacket(byteBuf, address)).sync();
            if(sync.isDone()){
               log.info("发送完成");
            }
            if(sync.isCancellable()){
                log.info("发送已取消");
            }
           if(sync.isSuccess()){
               log.info("发送成功");
           }else{
               log.info("发送失败:{}",sync.cause().getMessage());
           }
        } catch (InterruptedException e) {
            log.error("系统发送异常:{}",e.getMessage());
        }
    }
}
